package com.iqiyi.pps.epg.core.utils.puyu;

import org.apache.commons.codec.binary.Hex;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

//文件为通过jar包反编译生成
public class TripleDESUtil {

    private static final String ALGORITHM_NAME = "DESede";
    private static final String DEFAULT_CHAR_SET = "UTF-8";

    public static byte[] encrypt(String hexKey, String plainText) throws Exception {
        return encrypt(hex2Bytes(hexKey), plainText.getBytes(DEFAULT_CHAR_SET));
    }

    public static byte[] encrypt(byte key[], byte plainText[]) throws Exception {
        SecretKey deskey = new SecretKeySpec(key, ALGORITHM_NAME);
        Cipher cipher = Cipher.getInstance(ALGORITHM_NAME);
        cipher.init(1, deskey);
        return cipher.doFinal(plainText);
    }

    public static byte[] encrypt(String key, byte plainText[]) throws Exception {
        return encrypt(hex2Bytes(key), plainText);
    }

    public static String decrypt(String hexKey, String cryptographInHex) throws Exception {
        return decrypt(hex2Bytes(hexKey), hex2Bytes(cryptographInHex));
    }

    public static String decrypt(byte key[], byte cryptograph[]) throws Exception {
        SecretKey deskey = new SecretKeySpec(key, ALGORITHM_NAME);
        Cipher cipher = Cipher.getInstance(ALGORITHM_NAME);
        cipher.init(2, deskey);
        return new String(cipher.doFinal(cryptograph), DEFAULT_CHAR_SET);
    }

    public static String bytes2Hex(byte bytes[]) {
        return Hex.encodeHexString(bytes).toUpperCase();
    }

    public static byte[] hex2Bytes(String hex) throws Exception {
        return Hex.decodeHex(hex.toCharArray());
    }

    public static String generateKey() throws Exception {
        KeyGenerator kg = KeyGenerator.getInstance(ALGORITHM_NAME);
        kg.init(168);
        return bytes2Hex(kg.generateKey().getEncoded());
    }
}